<template>
	<div class="upload">
		<div class="haspic" v-if="value">
			<img :src="value">
			<a class="delPic" title="删除" @click="deletefile">X</a>
			<a class="showPic" title="放大" @click="$ImagePreview(value)"><i class="icon yanjing2"></i></a>
		</div>
		<div v-else class="dropbox">
			<input style="display: none;" ref="fileInput" type="file" multiple="multiple" accept="image/*" @change="getFile">
			<div @click="inputClick">
				<p class="text-center"><i class="h-icon-upload blue-color" v-font="30" ></i></p>
				<p class="text-center">点击或将文件拖拽到这里上传</p>
			</div>
			<div class="files" v-for="(file,index) in files" :key="index">
				<Progress :percent="file.uploadPercentage"><span slot="title">{{file.name}}</span><span slot="text"><span class="primary-color">{{file.uploadPercentage}}</span> %</span></Progress>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		props: {
			value: String,
			url: String
		},
		data() {
			return {
				files: []
			}
		},
		mounted() {
			let upload = document.querySelector('.upload')
			upload.addEventListener('dragenter', this.onDrag, false)
			upload.addEventListener('dragover', this.onDrag, false)
			upload.addEventListener('drop', this.onDrop, false)
		},
		methods: {
			inputClick(){
				this.$refs.fileInput.click()
			},
			getFile(){
				let dt = this.$refs.fileInput
				for (let i = 0; i !== dt.files.length; i++) {
					this.uploadFile(dt.files[i])
				}
			},
			async uploadFile(file) {
				let base64 = await this.$global.imageToBase64(file)
				let url = await this.$api('POST','upload',{name:file.name,base64:base64})
				if(url){
					this.$emit('input', url)
				}
			},
			onDrag(e) {
				e.stopPropagation()
				e.preventDefault()
			},
			onDrop(e) {
				e.stopPropagation()
				e.preventDefault()
				let dt = e.dataTransfer
				for (let i = 0; i !== dt.files.length; i++) {
					this.uploadFile(dt.files[i])
				}
			},
			deletefile(){
				this.$emit('input', '')
			}
		}
	}
</script>

<style lang='less'>
	.upload{
		.dropbox{
			box-sizing: border-box;
			border: 2px dashed #007bff;
			.files{
				border: 1px dashed #dddddd;
				margin: 10px;
				.h-progress-text{
					width: 50px;
				}
			}
		}
	}
	.haspic{
		width: 100%;
		max-height: 80px;
		min-height: 40px;
		img{
			width: 100%;
			max-height: 80px;
		}
		.delPic {
			position: absolute;
			z-index: 9999;
			right:0;
			background-color: #FF0000;
			color: #ffffff;
			width: 20px;
			height: 20px;
			text-align: center;
			border-radius: 0 4px 0 15px;
		}
		.showPic{
			position: absolute;
			z-index: 9999;
			bottom: 0px;
			right:0;
			background-color: #00aa00;
			color: #ffffff;
			width: 25px;
			height: 25px;
			line-height: 25px;
			text-align: center;
			border-radius:15px 0 4px 0;
			i {
				font-size:16px;
			}
		}
	}
</style>
